/* global BMap BMAP_SATELLITE_MAP BMAP_NORMAL_MAP */
import React, { useEffect, useState } from 'react'
import styles from '../index.module.less';

export default function Map(props) {
    const [map, setMap] = useState();
    const [overlay, setOverlay] = useState();
    useEffect(() => {
        loadMap();
    }, []);
    useEffect(() => {
        if (props.overlayVisible && map) {
            addOverlay(map);
        } else {
            map && map.removeOverlay(overlay);
        }
    }, [props.overlayVisible]);
    useEffect(() => {
        if (props.earthVisible) {
            map && map.setMapType(BMAP_SATELLITE_MAP);
        }
        else {
            map && map.setMapType(BMAP_NORMAL_MAP);
        }
    }, [props.earthVisible]);

    function addOverlay(map) {
        const paths = props.coordinates.map(item => {
            return new BMap.Point(item[0], item[1]);
        })
        const polygon = new BMap.Polygon(paths);
        // console.log(polygon);
        map.addOverlay(polygon);
        setOverlay(polygon);
    }

    function loadMap() {
        if (window.BMap) {
            initMap();
            return;
        }
        const script = document.createElement('script');
        document.body.appendChild(script);
        script.src = '//api.map.baidu.com/api?v=2.0&ak=1XjLLEhZhQNUzd93EjU5nOGQ&callback=_initBaiduMap';
        script.addEventListener('load', function () {
            window._initBaiduMap = initMap;
        });
    }

    function initMap() {
        // 百度地图API功能
        const map = new BMap.Map('bmap');  // 创建Map实例
        map.centerAndZoom('北京',8);
        map.enableScrollWheelZoom();
        map.addControl(new BMap.NavigationControl());
        setMap(map);
        props.overlayVisible && addOverlay(map);
    }

    return (
        <div id="bmap" className={styles.bmap}></div>
    )
}
